package com.yisu.expressway.ar;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.easy3d.core.ar.E3dARActivity;
import com.easy3d.core.ar.E3dARDataset;
import com.easy3d.core.ar.E3dARException;
import com.yisu.expressway.R;
import com.yisu.expressway.shopping_mall.YouZanWebActivity;
import com.yisu.expressway.ui.TitlebarLayout;
import com.yisu.expressway.ui.loading.CustomProgressDialog;
import com.yisu.expressway.utils.DisplayUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;


public class ARActivity extends E3dARActivity {

    private final static String TAG = ARActivity.class.getSimpleName();

    CustomProgressDialog mLoadingDialog;
    private View mTextLayoutView;
    private TextView mProductNameText;
    private TextView mProductBrandText;
    private TextView mProductPlaceText;
    private Button mBtn_buy;
    protected int NavigationBarHeight = 0;
    private Animation showAnimation;
    private Animation hideAnimation;
    protected ImageButton btnBack;

    @Override
    protected View getUILayout() {
        View uiLayout =  View.inflate(this, R.layout.ar_layout, null);
        mTextLayoutView = uiLayout.findViewById(R.id.textlayout);
        mProductNameText = (TextView) uiLayout.findViewById(R.id.prod_name);
        mProductBrandText = (TextView) uiLayout.findViewById(R.id.prod_brand);
        mProductPlaceText = (TextView) uiLayout.findViewById(R.id.prod_place);
        mBtn_buy = (Button)uiLayout.findViewById(R.id.btn_buy);
        btnBack = (ImageButton)uiLayout.findViewById(R.id.backBtn);
        if (btnBack != null) {
            btnBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }

        return uiLayout;
    }

    @Override
    protected E3dARDataset getARDataset() {

        return E3dARDataset.parse(this, E3dARDataset.STORAGE_APPRESOURCE, "ARAssets.json");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoadingDialog = new CustomProgressDialog(this);
        showLoading();
    }

    @Override
    public void onInitARDone(E3dARException e) {
        super.onInitARDone(e);
        dismissLoading();
        mProductDatas = new ArrayList<>();
        String json = getJson("ProductInfo.json");
        fillProductDatas(json);
        initAnimation();
    }

    @Override
    protected void onTrackerFound(String target) {
        final ProductData data = getProductDataByTarget(target);
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                changeUIProductInfo(data);
            }
        });

    }
    @Override
    protected void onTrackerLost(String target) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(mTextLayoutView !=null) {
                    mTextLayoutView.startAnimation(hideAnimation);
                    mTextLayoutView.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    private void initAnimation() {
        showAnimation = AnimationUtils.loadAnimation(this, R.anim.popup_show);
        showAnimation.setDuration(500);
        hideAnimation = AnimationUtils.loadAnimation(this, R.anim.popup_hide);
        hideAnimation.setDuration(500);
    }

    public class ProductData {
        public ArrayList<String> targets;
        public String name;
        public String brand;
        public String place;
        public String url;
        ProductData(){}
    }

    public ArrayList<ProductData> mProductDatas;
    private void fillProductDatas(String jsondata){

        try {
            JSONArray jDbs = new JSONArray(jsondata);
            Log.e(TAG,">>>>>>>json array"+jDbs.toString());
            for (int i = 0; i < jDbs.length(); i++) {
                ProductData data =new ProductData();
                JSONObject item = jDbs.getJSONObject(i);
                JSONObject jProd = item.getJSONObject("product_info");
                data.name = jProd.getString("name");
                data.brand = jProd.getString("brand");
                data.place = jProd.getString("place");
                data.url = jProd.getString("url");

                data.targets = new ArrayList<String>();
                JSONArray jTargets = item.getJSONArray("targets");
                for (int j = 0; j < jTargets.length(); j++) {
                    data.targets.add(jTargets.getString(j));
                }
                mProductDatas.add(i,data);
                Log.e(TAG,">>>>>>>>>data:"+data.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void changeUIProductInfo(final ProductData data){
        if(data == null){
            Log.e(TAG,"prodcut data is null");
            return;
        }
        mTextLayoutView.startAnimation(showAnimation);
        mTextLayoutView.setVisibility(View.VISIBLE);
        mProductNameText.setText(data.name);
        mProductBrandText.setText(data.brand);
        mProductPlaceText.setText(data.place);
        mBtn_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                YouZanWebActivity.launch(ARActivity.this,data.url,"");
            }
        });
    }

    public ProductData getProductDataByTarget(String target){
        for (int i=0;i<mProductDatas.size();i++) {
            ProductData data = mProductDatas.get(i);
            for(int j=0;j<data.targets.size();j++){
                if(data.targets.get(j).contentEquals(target)){
                    return data;
                }
            }
        }
        return null;
    }

    public  String getJson( String fileName) {
        StringBuilder sb = new StringBuilder();
        AssetManager am = this.getAssets();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    am.open(fileName)));
            String next = "";
            while (null != (next = br.readLine())) {
                sb.append(next);
            }
        } catch (IOException e) {
            e.printStackTrace();
            sb.delete(0, sb.length());
        }
        return sb.toString().trim();
    }

    /**
     * 显示默认loading
     */
    public void showLoading() {
        if(mLoadingDialog != null){
            mLoadingDialog.show();
            mLoadingDialog.showLoading();
        }
    }

    /**
     * 关闭loading
     */
    public void dismissLoading() {
        if(mLoadingDialog != null){
            mLoadingDialog.dismissLoading();
            mLoadingDialog.dismiss();
        }
    }

    protected void adjustModuleWidth(View view){
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        lp.height = DisplayUtil.dip2px(this,125) - NavigationBarHeight / 2;
        view.setLayoutParams(lp);
    }

}
